<template>
  <div class="localchk">
    <el-input placeholder="请输入详细地址查找" v-model="searchkey">
      <el-button slot="append" @click="searchLocal">查找</el-button>
    </el-input>
    <div id="map" style="margin-top: 10px" :style="{height:height}"></div>
  </div>
</template>

<script>
  window._AMapSecurityConfig = {
    securityJsCode: "e52080ccf79d7eb5b663c0a1ccc511d8",
  };
  import AMapLoader from "@amap/amap-jsapi-loader";
  export default {
    props: {
      //经纬度
      value: {
        type: String,
        default: "",
        // 119.692821, 29.099822
      },
      //具体地址
      address: {
        type: String,
        default: "",
      },
      // 地图高度
      height: {
        type: String,
        default: "300px",
      }
    },
    data() {
      return {
        searchkey: null,
        lnglat: [],
        marker: {},
        map: null,
        center: [],
      };
    },
    watch: {
      value: {
        immediate: true,
        handler(newValue) {
          if (newValue) {
            console.log(newValue, 'lnglat');
            this.lnglat = newValue.split(",");
            this.center = this.lnglat;
            if (this.map) {
              this.map.clearMap();
              this.map.add(
                new AMap.Marker({
                  position: [this.lnglat[0], this.lnglat[1]]
                })
              );
              this.map.setCenter(this.center);
            }
          } else {
            // console.log(newValue);
            this.lnglat = [];
            this.center = [119.65, 29.08];
            if (this.map) {
              this.map.clearMap();
              this.map.setCenter(this.center);
            }
          }
        }
      },
      address: {
        immediate: true,
        handler(newVal) {
          console.log(newVal, 'newAddress')
          if (newVal) {
            this.searchkey = newVal;
            if (this.map && !this.value) {
              this.searchLocal()
            }
          } else {
            this.searchkey = "";
          };
        }
      }
    },
    mounted() {
      if (this.value != undefined && this.value != "") {
        this.lnglat = this.value.split(",");
        this.center = this.lnglat;
      }
      this.setMap();
    },
    created() {},
    computed: {},
    methods: {
      setMap() {
        let that = this;
        AMapLoader.load({
            key: "9f5c5afddb467e683ecb1602c96e889e",
            version: "2.0",
            plugins: ["AMap.Geocoder"],
          })
          .then((AMap) => {
            let Geocoder = new AMap.Geocoder({});
            that.map = new AMap.Map("map", {
              zoom: 17,
              center: that.center || [119.65, 29.08],
              showIndoorMap: false,
            });
            if (that.address && !that.value) {
              that.searchLocal()
            }

            if (that.lnglat.length != 0) {
              that.map.add(
                new AMap.Marker({
                  position: that.lnglat,
                })
              );
            }
            that.map.on("click", function(e) {
              that.map.clearMap();
              let lng = e.lnglat.getLng(); //获取经度
              let lat = e.lnglat.getLat(); //获取纬度
              //经纬度转换为具体地址
              Geocoder.getAddress([lng, lat], function(status, result) {
                if (status === "complete" && result.info === "OK") {
                  console.log(result, 'result');
                  let address =
                    result.regeocode.addressComponent.district +
                    "" +
                    result.regeocode.addressComponent.township +
                    "" +
                    result.regeocode.addressComponent.street +
                    "" +
                    result.regeocode.addressComponent.streetNumber;
                  that.searchkey = result.regeocode.formattedAddress || address;
                  that.map.add(
                    new AMap.Marker({
                      position: [lng, lat],
                    })
                  );
                  that.$emit("input", {
                    lnglat: lng + "," + lat,
                    address: that.searchkey,
                  });
                }
              });
            });
          })
          .catch((e) => {
            console.log(e);
          });
      },
      searchLocal() {
        if (!this.searchkey) {
          this.$message.error("请输入要搜索的地址");
          return false;
        }
        let Geocoder = new AMap.Geocoder({});
        let that = this;
        Geocoder.getLocation(that.searchkey, function(status, result) {
          if (status === "complete" && result.info === "OK") {
            console.log(result, '地址result');
            that.lnglat = [
              result.geocodes[0].location.lng,
              result.geocodes[0].location.lat,
            ];
            let address = result.geocodes[0].formattedAddress.slice(6, result.geocodes[0].formattedAddress
              .length); //搜索地址
            let lnglat = that.lnglat.join(",");
            let formattedAddress = result.geocodes[0].formattedAddress;
            that.map.clearMap();
            that.$emit("input", { lnglat: lnglat, address: address, formattedAddress: formattedAddress });
            that.searchkey = formattedAddress;
            that.map.add(
              new AMap.Marker({
                position: that.lnglat,
              })
            );
            that.map.setFitView();
          } else {
            that.$message.error("无相关坐标信息");
            console.log("无相关坐标信息：", result);
          }
        });
      },
    },
  };
</script>

<style scoped lang="scss"></style>